import { getCampusTrainingData, getSchoolZoneEnrollments } from '@/api/campus/campus'
import { addFollowUp, getFollowUp, Info, updateFollowUp } from '@/api/campus/guidance'
import { DICTIONARY_TYPES, getDictionaryData } from '@/utils/dictionaryConstants'
export default {
  name: 'FollowUpDialog',
  props: {
    currentRow: {
      type: Object,
      default: () => ({})
    },
    isDetail: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      trainingDataLoading: false,
      dataForm: this.getInitialFormData(),
      rules: {
        followUpDate: [{ required: true, message: '请选择跟进时间', trigger: 'change' }],
        problemsSolved: [{ required: true, message: '请输入本次辅导为校区梳理解决的问题', trigger: 'blur' }, { min: 10, max: 1000, message: '问题描述长度在 10 到 1000 个字符', trigger: 'blur' }],
        currentProblems: [{ required: true, message: '请输入校区目前运营还有哪些问题', trigger: 'blur' }],
        hasOpeningCalendar: [{ required: true, message: '请选择校区是否有制作开业行事历', trigger: 'change' }],
        satisfaction: [{ required: true, message: '请选择满意度评价', trigger: 'change' }],
        enrollmentInfo: [{ required: true, message: '请输入落地辅导前招生情况', trigger: 'blur' }],
        commitment: [{ required: true, validator: (r, v, cb) => (v === true ? cb() : cb(new Error('请勾选承诺声明后再提交'))), trigger: 'change' }]
      },
      // 托管服务选项
      careServiceOptions: []
    }
  },
  async created() {
    // 加载托管服务选项
    await this.loadDictionaryData()
  },
  computed: {
    pageTitle() {
      return this.isDetail ? '回访详情' : this.editData ? '编辑回访' : '开业辅导回访记录'
    },
    isEditMode() {
      return !!this.editData
    }
  },
  watch: {
    // 监听托管服务和其他服务项目变化，自动计算月收入
    'dataForm.careServices': {
      handler: 'calculateMonthlyIncome',
      deep: true
    },
    'dataForm.otherServices': {
      handler: 'calculateMonthlyIncome',
      deep: true
    }
  },
  methods: {
    // 获取初始表单数据
        getInitialFormData() {
          return {
        id: '',
        campusId: '',
        followUpDate: '',
        guidanceDates: [],
        openingDate: '',
        teacherCount: 0,
        studentCount: 0,
        classCount: 0,
        normalStudentNum: 0,
        systemUsage: [],
        otherSystem: '',
        problemsSolved: '',
        currentProblems: '',
        hasOpeningCalendar: '',
        additionalContent: '',
        trainingData: [],
        satisfaction: 0,
        remark: '',
        guidanceId: '',
        // 招生数据统计相关字段
        enrollmentInfo: '',
        lunchCareCount: null,
        eveningCareCount: null,
        fullCareCount: null,
        summerCareCount: null,
        winterCareCount: null,
        preschoolCareCount: null,
        lunchCareFee: null,
        lunchFeeCycle: 'month',
        eveningCareFee: null,
        eveningFeeCycle: 'month',
        fullCareFee: null,
        fullFeeCycle: 'month',
        summerCareFee: null,
        summerFeeCycle: 'month',
        winterCareFee: null,
        winterFeeCycle: 'month',
        preschoolCareFee: null,
        preschoolFeeCycle: 'month',
        totalCareCount: 0,
        expectedIncome: '',
        // 托管服务项目（动态添加）
        careServices: [],
        otherServices: []
        ,
        commitment: true
      }
    },

    // 加载开业辅导招生数据统计
    async loadGuidanceEnrollmentStats(guidanceId) {
      try {
        this.loading = true
        const response = await Info(guidanceId)
        if (response && response.data) {
          const statsData = response.data

          // 填充招生数据统计相关字段
          this.dataForm.enrollmentInfo = statsData.enrollmentInfo || ''

          // 确保careServices数组已初始化
          if (!this.dataForm.careServices) {
            this.$set(this.dataForm, 'careServices', [])
          }

          // 清空现有托管服务项目列表
          this.dataForm.careServices = []

          // 基于数据字典动态加载托管服务项目
          if (this.careServiceOptions && this.careServiceOptions.length > 0) {
            // 遍历所有托管服务类型
            this.careServiceOptions.forEach(serviceOption => {
              const serviceCode = serviceOption.enCode

              const { countField, feeField, cycleField } = {
                countField: serviceCode + 'Count',
                feeField: serviceCode + 'Fee',
                cycleField: serviceCode.replace('Care', '') + 'FeeCycle'
              }

              // 检查后端数据中是否存在对应字段的值，且值不为0
              if (statsData[countField] !== null && statsData[countField] !== undefined && Number(statsData[countField]) > 0) {
                // 确保数据类型正确
                const studentCount = Number(statsData[countField]) || null
                const fee = parseFloat(statsData[feeField]) || null
                const feeCycle = statsData[cycleField] || 'month'

                // 只有当学生数量大于0且费用有效时才添加
                if (studentCount !== null && studentCount > 0 && fee !== null) {
                  // 添加到托管服务项目列表
                  this.dataForm.careServices.push({
                    serviceCode: serviceCode,
                    serviceName: serviceOption.fullName,
                    studentCount: studentCount,
                    fee: fee,
                    feeCycle: feeCycle
                  })
                }
              }
            })
          }

          // 填充其他服务项目
          if (statsData.otherServices && Array.isArray(statsData.otherServices)) {
            this.dataForm.otherServices = statsData.otherServices.map(service => ({
              serviceName: service.serviceName || '',
              studentCount: service.studentCount || 0,
              fee: service.fee || '',
              feeCycle: service.feeCycle || 'month'
            }))
          } else {
            this.dataForm.otherServices = []
          }

          // 更新托管总人数和预计收入
          this.calculateMonthlyIncome()

          // 直接设置预计收入（如果存在）
          if (statsData.expectedIncome) {
            this.dataForm.expectedIncome = statsData.expectedIncome
          }

          // 直接设置托管总人数（如果存在）
          if (statsData.totalCareCount) {
            this.dataForm.totalCareCount = statsData.totalCareCount
          }

          // 设置其他字段
          if (statsData.teacherCount !== undefined) this.dataForm.teacherCount = statsData.teacherCount
          if (statsData.studentCount !== undefined) this.dataForm.studentCount = statsData.studentCount
          if (statsData.classCount !== undefined) this.dataForm.classCount = statsData.classCount
          if (statsData.trainingData !== undefined) this.dataForm.trainingData = statsData.trainingData || []
        }
      } catch (error) {
        console.error('加载开业辅导招生数据统计失败:', error)
        this.$message.error('加载开业辅导招生数据统计失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },

    // 提交前处理数据，将动态托管服务项目映射到对应字段
    processCareServicesBeforeSubmit() {
      // 遍历动态托管服务项目，映射到对应字段
      this.dataForm.careServices.forEach(service => {
        const serviceType = service.serviceCode
        this.dataForm[`${serviceType}Count`] = null
        // 映射收费
        this.dataForm[`${serviceType}Fee`] = null
        // 映射收费周期
        this.dataForm[`${serviceType.replace('Care', '')}FeeCycle`] = null

        if (serviceType !== null && serviceType !== undefined) {
          // 映射人数
          this.dataForm[`${serviceType}Count`] = parseInt(service.studentCount) || null

          // 映射收费
          this.dataForm[`${serviceType}Fee`] = service.fee || null

          // 映射收费周期
          this.dataForm[`${serviceType.replace('Care', '')}FeeCycle`] = service.feeCycle || 'month'
        }
      })

      // 确保careServices是数组格式而非字符串
      if (this.dataForm.careServices && typeof this.dataForm.careServices === 'string') {
        try {
          this.dataForm.careServices = JSON.parse(this.dataForm.careServices)
        } catch (e) {
          console.error('解析careServices失败:', e)
          this.dataForm.careServices = []
        }
      }
    },

    // 布尔值转换工具方法
    convertBooleanFields(data, toBoolean = false) {
      const booleanFields = ['hasOpeningCalendar']
      const result = { ...data }

      booleanFields.forEach(field => {
        if (toBoolean) {
          result[field] = data[field] === 'true' || data[field] === true
        } else {
          result[field] = data[field] === true || data[field] === 'true' ? 'true' : 'false'
        }
      })

      return result
    },

    // 准备提交数据
    prepareSubmitData() {
      // 先处理托管服务项目映射
      this.processCareServicesBeforeSubmit()

      const submitData = { ...this.dataForm }

      // 确保careServices是数组格式而非字符串
      if (submitData.careServices && typeof submitData.careServices === 'string') {
        try {
          submitData.careServices = JSON.parse(submitData.careServices)
        } catch (e) {
          console.error('解析careServices失败:', e)
          submitData.careServices = []
        }
      }

      // 确保otherServices是数组格式而非字符串
      if (submitData.otherServices && typeof submitData.otherServices === 'string') {
        try {
          submitData.otherServices = JSON.parse(submitData.otherServices)
        } catch (e) {
          console.error('解析otherServices失败:', e)
          submitData.otherServices = []
        }
      }

      // 确保systemUsage是数组格式而非字符串
      if (submitData.systemUsage && typeof submitData.systemUsage === 'string') {
        try {
          submitData.systemUsage = JSON.parse(submitData.systemUsage)
        } catch (e) {
          console.error('解析systemUsage失败:', e)
          submitData.systemUsage = []
        }
      }

      // 转换布尔值字段
      const booleanConverted = this.convertBooleanFields(submitData, true)

      return {
        ...booleanConverted,
        id: submitData.id || undefined,
        guidanceId: submitData.guidanceId,
        trainingData: submitData.trainingData || [] // 直接传递数组，不转换为JSON字符串
      }
    },

    // 加载字典数据
    async loadDictionaryData() {
      this.careServiceOptions = await getDictionaryData(DICTIONARY_TYPES.CARE_SERVICE)
    },

    // 添加托管服务项目
    async addCareService() {
      this.dataForm.careServices.push({
        serviceCode: '',
        serviceName: '',
        studentCount: 0,
        fee: '',
        feeCycle: 'month'
      })
    },

    // 移除托管服务项目
    removeCareService(index) {
      this.dataForm.careServices.splice(index, 1)
      this.calculateMonthlyIncome()
    },

    // 添加其他收费项目
    addOtherService() {
      this.dataForm.otherServices.push({
        serviceName: '',
        studentCount: 0,
        fee: '',
        feeCycle: 'month'
      })
    },

    // 移除其他收费项目
    removeOtherService(index) {
      this.dataForm.otherServices.splice(index, 1)
      this.calculateMonthlyIncome()
    },

    // 托管服务类型变更处理
    onCareServiceChange(index) {
      const service = this.dataForm.careServices[index]
      if (!service) return

      // 根据选择的服务类型设置服务名称
      const option = this.careServiceOptions.find(opt => opt.enCode === service.serviceCode)
      if (option) {
        service.serviceName = option.fullName
      }

      this.calculateMonthlyIncome()
    },

    // 检查服务类型是否已被使用
    isServiceTypeUsed(code, currentIndex) {
      return this.dataForm.careServices.some((item, index) => index !== currentIndex && item.serviceCode === code)
    },

    // 托管服务收费变更处理
    onCareServiceFeeChange(index) {
      this.calculateMonthlyIncome()
    },

    // 其他服务收费变更处理
    onOtherServiceFeeChange(index) {
      this.calculateMonthlyIncome()
    },

    // 计算月收入和托管总人数
    calculateMonthlyIncome() {
      let totalMonthlyIncome = 0
      let totalCareCount = 0

      // 计算托管服务月收入和总人数
      if (this.dataForm.careServices && this.dataForm.careServices.length > 0) {
        this.dataForm.careServices.forEach(service => {
          const count = Number(service.studentCount || 0)
          const fee = parseFloat(service.fee || 0)
          const cycle = service.feeCycle || 'month'

          // 累加托管总人数
          totalCareCount += count

          // 根据周期转换为月收入
          let monthlyFee = fee
          if (cycle === 'semester') {
            monthlyFee = fee / 4.5 // 学期约4.5个月
          } else if (cycle === 'week') {
            monthlyFee = fee * 4 // 一个月约4周
          }

          totalMonthlyIncome += monthlyFee * count
        })
      }

      // 更新托管总人数
      this.dataForm.totalCareCount = totalCareCount

      // 计算其他服务月收入
      if (this.dataForm.otherServices && this.dataForm.otherServices.length > 0) {
        this.dataForm.otherServices.forEach(service => {
          const count = Number(service.studentCount || 0)
          const fee = parseFloat(service.fee || 0)
          const cycle = service.feeCycle || 'month'

          // 根据周期转换为月收入
          let monthlyFee = fee
          if (cycle === 'semester') {
            monthlyFee = fee / 4.5 // 学期约4.5个月
          } else if (cycle === 'week') {
            monthlyFee = fee * 4 // 一个月约4周
          }

          totalMonthlyIncome += monthlyFee * count
        })
      }

      // 更新预计月收入
      this.dataForm.expectedIncome = totalMonthlyIncome.toFixed(2)
    },

    // 解析辅导日期（兼容数组、JSON 字符串、逗号/中文分隔字符串）
    parseGuidanceDates(guidanceDates) {
      if (!guidanceDates) return ''
      try {
        // 数组直接处理
        if (Array.isArray(guidanceDates)) {
          const arr = guidanceDates.map(d => String(d).trim()).filter(Boolean)
          return arr.length > 0 ? arr.join('、') : ''
        }
        // 字符串：尝试 JSON 解析，否则按分隔符切分
        if (typeof guidanceDates === 'string') {
          const str = guidanceDates.trim()
          if (!str) return ''
          let arr = []
          // 优先尝试解析为 JSON 数组字符串
          try {
            // 只有当字符串以 [ 开头且以 ] 结尾时才尝试JSON解析
            if (str.startsWith('[') && str.endsWith(']')) {
              const parsed = JSON.parse(str)
              if (Array.isArray(parsed)) {
                arr = parsed
              }
            } else {
              // 非 JSON 字符串，按常见分隔符拆分：逗号、顿号、中文分隔符、空白
              arr = str.split(/[\,\u3001、\s]+/)
            }
          } catch (e) {
            // JSON 解析失败，按常见分隔符拆分
            arr = str.split(/[\,\u3001、\s]+/)
          }
          arr = arr.map(d => String(d).trim()).filter(Boolean)
          return arr.length > 0 ? arr.join('、') : ''
        }
        // 其他类型不支持
        return ''
      } catch (error) {
        console.warn('解析辅导日期失败:', error)
        return ''
      }
    },

    // 加载校区数据（合并基础数据和培训数据加载）
        async loadSchoolZoneData() {
      if (!this.currentRow.campusId) return

      this.trainingDataLoading = true
      try {
        const { data } = await getSchoolZoneEnrollments(this.currentRow.campusId)
        if (data) {
          // 字段映射：后端返回teacherNum/studentNum/classNum，前端使用teacherCount/studentCount/classCount
          Object.assign(this.dataForm, {
            teacherCount: data.teacherNum || 0, // 在职老师数量
            studentCount: data.studentNum || 0, // 在校学生数量
            classCount: data.classNum || 0, // 创建班级数量
            normalStudentNum: data.normalStudentNum || 0,
            trainingData: data.trainingData || []
          })
        }
      } catch (error) {
        console.error('获取校区数据失败:', error)
        this.dataForm.trainingData = []
      } finally {
        this.trainingDataLoading = false
      }
    },

    // 加载培训数据（模板中引用的方法）
    async loadTrainingData() {
      if (!this.currentRow.campusId) {
        this.$message.warning('请先选择校区')
        return
      }

      this.trainingDataLoading = true
      try {
        const { data } = await getCampusTrainingData(this.currentRow.campusId)
        if (data && data.length > 0) {
          this.dataForm.trainingData = data
        } else {
          this.dataForm.trainingData = []
        }
      } catch (error) {
        console.error('获取培训数据失败:', error)
        this.$message.error('获取参训数据失败')
        this.dataForm.trainingData = []
      } finally {
        this.trainingDataLoading = false
      }
    },

    /**
     * 将后端数据转换为托管服务项目列表
     * 基于数据字典动态加载托管服务项目数据
     */
    convertBackendDataToCareServices(editData) {
      // 确保careServices数组已初始化
      if (!this.dataForm.careServices) {
        this.$set(this.dataForm, 'careServices', [])
      }

      // 清空现有托管服务项目列表
      this.dataForm.careServices = []

      // 检查是否有直接的careServices数据
      if (editData.careServices && Array.isArray(editData.careServices) && editData.careServices.length > 0) {
        // 直接使用已有的careServices数据
        editData.careServices.forEach(service => {
          if (service && service.serviceCode) {
            this.dataForm.careServices.push({
              serviceCode: service.serviceCode,
              serviceName: service.serviceName || this.getServiceNameByCode(service.serviceCode),
              studentCount: Number(service.studentCount) || 0,
              fee: parseFloat(service.fee) || 0,
              feeCycle: service.feeCycle || 'month'
            })
          }
        })
        return this.dataForm.careServices
      }

      // 基于数据字典动态加载托管服务项目
      if (this.careServiceOptions && this.careServiceOptions.length > 0) {
        // 遍历所有托管服务类型
        this.careServiceOptions.forEach(serviceOption => {
          const serviceCode = serviceOption.enCode

          const { countField, feeField, cycleField } = {
            countField: serviceCode + 'Count',
            feeField: serviceCode + 'Fee',
            cycleField: serviceCode.replace('Care', '') + 'FeeCycle'
          }

          // 检查后端数据中是否存在对应字段的值，且值不为0
          if (editData[countField] !== null && editData[countField] !== undefined && Number(editData[countField]) > 0) {
            // 确保数据类型正确
            const studentCount = Number(editData[countField]) || 0
            const fee = parseFloat(editData[feeField]) || 0
            const feeCycle = editData[cycleField] || 'month'

            // 只有当学生数量大于0时才添加
            if (studentCount > 0) {
              // 添加到托管服务项目列表
              this.dataForm.careServices.push({
                serviceCode: serviceCode,
                serviceName: this.getServiceNameByCode(serviceCode),
                studentCount: studentCount,
                fee: fee,
                feeCycle: feeCycle
              })
            }
          }
        })
      }

      return this.dataForm.careServices
    },

    // 根据服务代码获取服务名称
    getServiceNameByCode(code) {
      if (!code || !this.careServiceOptions) return ''
      const option = this.careServiceOptions.find(opt => opt.enCode === code)
      return option ? option.fullName : code
    },

    // 重建托管服务项目校验规则
    rebuildCareServiceRules() {
      // 构建托管服务项目校验规则
      const careServicesRules = {}

      if (this.dataForm.careServices) {
        this.dataForm.careServices.forEach((_, index) => {
          careServicesRules[`careServices.${index}.serviceCode`] = [{ required: true, message: '请选择托管服务类型', trigger: 'change' }]
          careServicesRules[`careServices.${index}.studentCount`] = [{ required: true, message: '请输入招生人数', trigger: 'blur' }]
          careServicesRules[`careServices.${index}.fee`] = [{ required: true, message: '请输入费用', trigger: 'blur' }]
        })
      }

      // 更新校验规则
      this.$refs.dataForm && this.$refs.dataForm.clearValidate && this.$refs.dataForm.clearValidate()
    },

    // 返回上一页
    goBack() {
      this.$emit('close')
    },

    /**
     * 统一入口方法：显示回访对话框
     * @param {Object} row 当前行数据
     * @param {Boolean} isEdit 是否为编辑模式
     * @param {Boolean} isDetailMode 是否为详情模式
     */
    async showFollowUpDialog(row, isEdit = false, isDetailMode = false) {
      // 重置表单数据
      this.dataForm = this.getInitialFormData()

      // 设置当前行数据
      this.$emit('update:currentRow', row)

      // 设置模式
      this.$emit('update:isDetail', isDetailMode)

      if (isEdit && row.followUp) {
        // 编辑模式：加载历史数据
        await this.loadFollowUpDetail(row.id)
        if (row.campusId) {
          await this.loadSchoolZoneData()
          await this.loadTrainingData()
        }
      } else if (isDetailMode && row.id) {
        // 详情模式：加载数据
        await this.loadFollowUpDetail(row.id)
      } else {
        // 新增模式：自动加载开业辅导招生数据统计
        if (row.id) {
          await this.loadGuidanceEnrollmentStats(row.id)
        }
        if (row.campusId) {
          await this.loadSchoolZoneData()
          await this.loadTrainingData()
        }
      }

      // 确保加载落地辅导日期和开业日期
      this.loadGuidanceDatesAndOpeningDate()
    },

    // 加载回访详情数据
    async loadFollowUpDetail(guidanceId) {
      this.loading = true
      try {
        const response = await getFollowUp(guidanceId)
        if (response && response.data) {
          const data = response.data

          // 修复对象展开语法错误
          Object.assign(this.dataForm, data)

          // 如果没有careServices数据，则从单独的字段构建
          if (!this.dataForm.careServices || this.dataForm.careServices.length === 0) {
            this.convertBackendDataToCareServices(data)
          }

          this.calculateMonthlyIncome()
          this.rebuildCareServiceRules()
        }
      } catch (error) {
        console.error('获取回访详情失败:', error)
        this.$message.error('获取回访详情失败')
      } finally {
        this.loading = false
      }
    },

    /**
     * 解析落地辅导日期
     * @returns {Array} 解析后的日期数组
     */
    parseGuidanceDates() {
      let guidanceDates = []
      if (this.currentRow && this.currentRow.guidanceDates) {
        if (typeof this.currentRow.guidanceDates === 'string') {
          try {
            // 尝试直接解析JSON字符串
            const parsed = JSON.parse(this.currentRow.guidanceDates)
            if (Array.isArray(parsed)) {
              guidanceDates = parsed
            }
          } catch (e) {
            console.warn('解析guidanceDates失败:', e)
            // 尝试其他可能的格式，如逗号分隔的字符串
            if (this.currentRow.guidanceDates.includes(',')) {
              guidanceDates = this.currentRow.guidanceDates.split(',')
            }
          }
        } else if (Array.isArray(this.currentRow.guidanceDates)) {
          guidanceDates = this.currentRow.guidanceDates
        }
      }
      return guidanceDates
    },

    /**
     * 加载落地辅导日期和开业日期
     */
    loadGuidanceDatesAndOpeningDate() {
      // 确保加载落地辅导日期
      if (!this.dataForm.guidanceDates || this.dataForm.guidanceDates.length === 0) {
        this.dataForm.guidanceDates = this.parseGuidanceDates()
      }

      // 确保加载开业日期
      if (!this.dataForm.openingDate) {
        this.dataForm.openingDate = (this.currentRow && this.currentRow.openingDate) || ''
      }
    },

    // 满意度评价变化处理
    onSatisfactionChange(value) {
      // 当评分变化时触发，用于实时更新显示
      this.$forceUpdate()
    },

    // 获取满意度评价标签
    getSatisfactionLabel() {
      const rating = this.dataForm.satisfaction
      if (rating >= 9 && rating <= 10) {
        return '非常满意'
      } else if (rating === 8) {
        return '基本满意'
      } else if (rating === 7) {
        return '一般'
      } else if (rating >= 1 && rating <= 6) {
        return '不太满意'
      }
      return ''
    },

    // 获取满意度评价标签样式类
    getSatisfactionLabelClass() {
      const rating = this.dataForm.satisfaction
      if (rating >= 9 && rating <= 10) {
        return 'label-very-satisfied'
      } else if (rating === 8) {
        return 'label-satisfied'
      } else if (rating === 7) {
        return 'label-average'
      } else if (rating >= 1 && rating <= 6) {
        return 'label-unsatisfied'
      }
      return ''
    },

    // 获取满意度评价标签内联样式（备用方案）
    getSatisfactionLabelStyle() {
      const rating = this.dataForm.satisfaction
      const baseStyle = {
        fontSize: '14px',
        fontWeight: '600',
        padding: '4px 8px',
        borderRadius: '4px',
        color: 'white'
      }

      if (rating >= 1 && rating <= 2) {
        return { ...baseStyle, backgroundColor: '#f56c6c' }
      } else if (rating >= 3 && rating <= 4) {
        return { ...baseStyle, backgroundColor: '#e6a23c' }
      } else if (rating >= 5 && rating <= 7) {
        return { ...baseStyle, backgroundColor: '#67c23a' }
      } else if (rating >= 8 && rating <= 10) {
        return { ...baseStyle, backgroundColor: '#409eff' }
      }
      return baseStyle
    },

    // 提交表单
    async dataFormSubmit() {
      const valid = await this.$refs.elForm.validate().catch(() => false)
      if (!valid) {
        this.$message.warning('请完善必填信息')
        return
      }

      this.loading = true
      try {
        const submitData = this.prepareSubmitData()
        if (this.$refs.elForm && this.isDetail === false) {
          // 额外校验：提交前必须勾选承诺声明
          if (submitData.commitment !== true) {
            this.$message.error('请勾选承诺声明后再提交')
            this.loading = false
            return
          }
        }
        // 使用开业辅导记录的主键ID，而不是校区ID
        const guidanceId = this.currentRow && this.currentRow.id

        if (!guidanceId) {
          throw new Error('开业辅导ID不能为空')
        }
        // 确保提交数据包含必要字段
        submitData.guidanceId = guidanceId
        submitData.campusId = this.currentRow.campusId
        let res
        if (this.isEditMode) {
          res = await updateFollowUp(guidanceId, submitData)
        } else {
          res = await addFollowUp(guidanceId, submitData)
        }

        if (res && res.code === 200) {
          this.$message.success(this.isEditMode ? '更新成功' : '添加成功')
          this.$emit('refresh')
          this.goBack()
        } else {
          throw new Error((res && res.message) || '操作失败')
        }
      } catch (error) {
        console.error('提交失败:', error)
        let errorMessage = this.isEditMode ? '更新失败' : '添加失败'

        // 处理不同类型的错误
        if (error && error.response) {
          // HTTP错误响应
          const responseData = error.response.data || {}
          errorMessage = responseData.message || responseData.msg || `请求失败 (${error.response.status})`
        } else if (error && error.message) {
          // JavaScript Error对象
          errorMessage = error.message
        } else if (typeof error === 'string') {
          // 字符串错误
          errorMessage = error
        } else if (error && typeof error === 'object') {
          // 其他对象类型错误
          errorMessage = JSON.stringify(error)
        }

        this.$message.error(errorMessage)
      } finally {
        this.loading = false
      }
    }
  }
}
